#!/bin/bash
# tools to run dmctl from command line
# parameter 1: work directory
# parameter 2: master-addr port
# parameter 3: command
# parameter 4...: check output content and count

workdir=$1
master_addr=$2
cmd=$3

shift 3

PWD=$(pwd)
binary=$PWD/bin/dmctl.test
ts=$(date +"%s")
dmctl_log=$workdir/dmctl.$ts.log
pid=$$

echo "dmctl test cmd: \"$cmd\""

all_matched=true
for ((k = 0; k < 10; k++)); do
	echo "$cmd" | $binary -test.coverprofile="$TEST_DIR/cov.$TEST_NAME.dmctl.$ts.$pid.out" DEVEL --master-addr=$master_addr >$dmctl_log 2>&1
	all_matched=true
	for ((i = 1; i < $#; i += 2)); do
		j=$((i + 1))
		value=${!i}
		expected=${!j}
		# Count total number of value's occurrences in log file. value can be a regular expression with newline.
		# See https://stackoverflow.com/questions/1251999/how-can-i-replace-a-newline-n-using-sed.
		got=$(grep -Pzo "$value" "$dmctl_log" | sed ":a;N;\$!ba;s/\n//g" | sed 's/\x00/\n/g' | wc -l)
		if [ "$got" != "$expected" ]; then
			echo "command: $cmd $value count: $got != expected: $expected, failed the $k-th time, will retry again"
			all_matched=false
			break
		fi
	done

	if $all_matched; then
		exit 0
	fi

	sleep 2
done

cat $dmctl_log
exit 1
